package document;

import java.util.Collections;
import java.util.Iterator;
import java.util.Vector;

public class Posting {
	private int docID;
	private Vector<Integer> occurencies;
	private Posting matchedPosting;
	private int termFrequency;

	public Posting(int docID) {
		this.docID = docID;
		this.occurencies = new Vector<Integer>();
		termFrequency = 0;
	}

	public void addOccurence(int position) {
		if (!occurencies.contains(position)) {
			occurencies.add(position);
			termFrequency++;
		}
	}

	public int getDocID() {
		return docID;
	}

	public Vector<Integer> getOccurencies() {
		return occurencies;
	}
	
	public int getTermFrequency()
	{
		return termFrequency;
	}
	
	/**
	 * Call this only after isWithinWindow() to get the matched postings
	 * @return
	 */
	public Posting getMatchedPostings()
	{
		return matchedPosting;
	}

	public boolean isWithinWindow(Posting otherPosting, int windowSize) {

		matchedPosting = new Posting(otherPosting.docID);
		if (docID != otherPosting.getDocID()) {
			return false;
		}

		int maxDistance = windowSize - 1;
		Vector<Integer> occurenciesOther = otherPosting.getOccurencies();

		Collections.sort(occurenciesOther);
		Collections.sort(occurencies);

		Iterator<Integer> itThis = occurencies.iterator();
		Iterator<Integer> itOther = occurenciesOther.iterator();
		int thisOcc = itThis.next();
		int otherOcc = itOther.next();

		boolean foundMatch = false;
		boolean testedAll = false;
		int lastMatchedOccurence = -1;
		do {

			if (otherOcc - thisOcc > 0 && otherOcc - thisOcc <= maxDistance && lastMatchedOccurence != otherOcc) {
				matchedPosting.addOccurence(otherOcc);
				lastMatchedOccurence = otherOcc;
				foundMatch = true;
			} else if (thisOcc < otherOcc && itThis.hasNext()) {
				thisOcc = itThis.next();
			} else if (thisOcc > otherOcc && itOther.hasNext()){
				otherOcc = itOther.next();
			}
			else
			{
				testedAll = true;
			}
		} while (!testedAll);
		return foundMatch;
	}
}
